﻿using Llp_shop.Models;
using Llp_shop.Models.Database;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Llp_shop.Serives
{ /// <summary>
  /// 购物车服务类
  /// </summary>
    public class CarService : ICarService
    {
        private readonly IDatabase _redis;
        private readonly shop_BContext _db;
        public CarService(RedisHelper client, shop_BContext db)
        {
            //创建Redis连接对象
            _redis = client.GetDatabase();
            _db = db;
        }
        //购物车相关方法

        /// <summary>
        /// 添加购物车
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="goodId"></param>
        public void AddCar(string userId, int goodId)
        {
            //1、用户购车的key
            var key = "UserCar" + userId;
            //添加购物车数量
            _redis.HashIncrement(key, goodId);
        }
        /// <summary>
        /// 减少购物车数量
        /// </summary>
        public void DiffCar(string userId, int goodId)
        {
            //1、用户购车的key
            var key = "UserCar" + userId;
            //减少hash里对应商品Id的值 -1
            var value = _redis.HashDecrement(key, goodId);
            //如果减少后等于0 时 就要删除   -1 
            if (value <= 0)
            {
                //删除
                _redis.HashDelete(key, goodId);
            }

        }
        /// <summary>
        /// 移除购物车商品
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="goodId"></param>
        public void RemoveCar(string userId, int goodId)
        {
            //1、用户购车的key
            var key = "UserCar" + userId;
            //a删除
            _redis.HashDelete(key, goodId);
        }
        /// <summary>
        /// 获取购物车商品
        /// </summary>
        /// <returns></returns>
        public List<CarGoods> GetCarGoods(string userId)
        {
            var list = new List<CarGoods>();
            //1、用户购车的key
            var key = "UserCar" + userId;
            var hashData = _redis.HashGetAll(key);
            //循环遍历 取出来的hash数组 
            //商品Id  数量
            //2         1
            //10        2
            foreach (var item in hashData)
            {
                //item.Name 商品 Id  
                //item.Value 商品 数量
                //a通过商品Id查询商品的标题和图片
                var good = _db.Goods.FirstOrDefault(x => x.GoodId == (int)item.Name);
                if (good != null)
                {
                    list.Add(new CarGoods()
                    {
                        GoodId = (int)item.Name,
                        Count = (int)item.Value,
                        Title = good.Title,
                        Photo = good.Photo,
                        Price = good.Price
                    });
                }
            }
            return list;
        }

    }
}
